package com.zhida.jiyangcenter.account

import android.graphics.Color
import android.graphics.Typeface
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextWatcher
import android.text.method.HideReturnsTransformationMethod
import android.text.method.LinkMovementMethod
import android.text.method.PasswordTransformationMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.lifecycle.lifecycleScope
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.manager.app
import chooongg.base.utils.*
import chooongg.base.widget.backlayout.ParallaxBackEnable
import chooongg.http.APIException
import cn.sharesdk.framework.Platform
import cn.sharesdk.framework.PlatformActionListener
import cn.sharesdk.framework.ShareSDK
import cn.sharesdk.wechat.friends.Wechat
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.WebNoTokenActivity
import com.zhida.jiyangcenter.WebNoTokenActivity.Companion.TITLE
import com.zhida.jiyangcenter.WebNoTokenActivity.Companion.URL
import com.zhida.jiyangcenter.api.APIAccount
import com.zhida.jiyangcenter.api.BaseAPI
import com.zhida.jiyangcenter.api.LoginEntity
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.mian.MainActivity
import com.zhida.jiyangcenter.utils.REGEX_PASSWORD
import com.zhida.jiyangcenter.utils.SP
import com.zhida.jiyangcenter.utils.request
import kotlinx.android.synthetic.main.activity_login_pass.*
import kotlinx.android.synthetic.main.activity_login_pass.btn_wechat
import kotlinx.android.synthetic.main.activity_login_pass.tv_login_xieyi
import kotlinx.android.synthetic.main.activity_login_pass.tv_title

import kotlinx.coroutines.launch

@TitleBar(false)
@ParallaxBackEnable(false)
@ContentLayout(R.layout.activity_login_pass)
class LoginPassActivity : BaseActivity() {
    override fun initConfig(savedInstanceState: Bundle?) {
        val window = activity.window
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            window.decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR

        tv_title.setText("welcome".style { } + "\n欢迎来到中昊云景".style {
            setTextSizeRelative(0.5f)
            setTextStyle(Typeface.NORMAL)
        })
        showSoftInput(edit_phone)
        edit_phone.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) = Unit
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) =
                Unit

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (edit_phone.text.isNullOrEmpty()) {
                    iv_phone_clear.animate().alpha(0f)
                    iv_phone_clear.isClickable = false
                } else {
                    iv_phone_clear.animate().alpha(1f)
                    iv_phone_clear.isClickable = true
                }

                edit_password.text = null
                btn_login.setTextColor(Color.parseColor("#B2FFFFFF"))
            }
        })
        val styles = SpannableStringBuilder() //设置文字
        val s = "登录注册即代表同意《用户使用协议》《隐私政策说明条款》"
        styles.append(s)
        val clickableSpans = object : ClickableSpan() {
            override fun onClick(widget: View) {
                startActivity<WebNoTokenActivity> {
                    putExtra(WebNoTokenActivity.URL,"http://beauty.hebzd.com/static/xieyi/userAgreement.html")
                    putExtra(WebNoTokenActivity.TITLE,"用户使用协议")
                }
            }
        }
        styles.setSpan(clickableSpans, 9, 17, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        val foregroundColorSpans = ForegroundColorSpan(Color.parseColor("#1296DB"))
        styles.setSpan(foregroundColorSpans, 9, 17, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) //配置给TextView
        val clickableSpan1 = object : ClickableSpan() {
            override fun onClick(widget: View) {
                startActivity<WebNoTokenActivity> {
                    putExtra(WebNoTokenActivity.URL, "http://beauty.hebzd.com/static/xieyi/privacy.html")
                    putExtra(WebNoTokenActivity.TITLE, "隐私政策说明条款")
                }
            }
        }
        styles.setSpan(clickableSpan1, 18, styles.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        val foregroundColorSpan1 = ForegroundColorSpan(Color.parseColor("#1296DB"))
        styles.setSpan(foregroundColorSpan1, 18, styles.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) //配置给TextView
        tv_login_xieyi.movementMethod = LinkMovementMethod.getInstance()
        tv_login_xieyi.text=styles
        edit_phone.setText(intent.getStringExtra("phone"))
        edit_password.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) = Unit
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) =
                Unit

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (edit_phone.text.regex(RegexConstants.REGEX_MOBILE_EXACT) && edit_password.text.regex(
                        REGEX_PASSWORD
                    )
                ) {
                    btn_login.setTextColor(Color.WHITE)
                } else btn_login.setTextColor(Color.parseColor("#B2FFFFFF"))
            }
        })
        edit_phone.setOnEditorActionListener { _, actionId, _ ->
            return@setOnEditorActionListener if (actionId == EditorInfo.IME_ACTION_NEXT) {
                showSoftInput(edit_password)
                true
            } else false
        }
        edit_password.setOnEditorActionListener { _, actionId, _ ->
            return@setOnEditorActionListener if (actionId == EditorInfo.IME_ACTION_DONE) {
                passwordLogin(edit_phone.text.toString(), edit_password.text.toString())
                true
            } else false
        }
        eventConfig()
        btn_wechat.setOnClickListener {
            val wechat = ShareSDK.getPlatform(Wechat.NAME)
            if (wechat.isAuthValid) wechat.removeAccount(true)// 解除本地授权信息
            //SSO授权，传false默认是客户端授权
            wechat.SSOSetting(false);
            wechat.platformActionListener = object : PlatformActionListener {
                override fun onComplete(
                    platform: Platform,
                    action: Int,
                    res: HashMap<String, Any>
                ) {
                    showTipLoading("登录中")
                    if (action == Platform.ACTION_USER_INFOR) {
                        wechatLogin(res["openid"].toString())
                    }
                }

                override fun onCancel(p0: Platform?, p1: Int) {
                    toast("取消授权")
                }

                override fun onError(p0: Platform?, errorCode: Int, e: Throwable?) {
                    toast("授权失败\n错误码：$errorCode")
                    Log.e("SDFSDFSDF", "dfwetwesfsdf", e)
                    e?.printStackTrace()
                }
            }
            wechat.showUser(null)
        }
    }

    private fun wechatLogin(toString: String) {
        lifecycleScope.request({ APIAccount.service().weCharLogin(toString) },
            object : BaseAPI<LoginEntity>() {
                override fun onSuccess(loginEntity: LoginEntity?, state: Int, msg: String) {
                    hideTipLoading()
                    if (loginEntity == null) {

                    } else {
                        tipSuccess(msg)
                        SP.isLogin.put(true)
                        SP.key_id.put(loginEntity.key_id)
                        SP.account.put(loginEntity.account)
                        SP.avatar.put(loginEntity.avatar)
                        SP.EBusinessID.put(loginEntity.business_id)
                        SP.AppKey.put(loginEntity.app_key)
                        SP.ReqURL.put(loginEntity.req_url)
//                        if (!SP.ISYinsi.get()) {
//                            startActivity<WebNoTokenActivity> {
//                                putExtra(URL, "http://beauty.hebzd.com/static/xieyi/privacy.html")
//                                putExtra(TITLE, "隐私协议")
//                            }
//                        } else {
                            startActivity<MainActivity> { }
//                        }
                        for (i in app.activityStack.size - 1 downTo 0) {
                            if (app.activityStack[i] !is MainActivity) {
                                app.activityStack[i].finish()
                            }
                        }
                        finish()
                    }
                }

                override fun onError(e: APIException) {
                    hideTipLoading()
                    if (e.code == "-9") {
                        startActivity<LoginPhoneActivity> {
                            putExtra("wechat_openid", toString)
                        }
                    } else {
                        tipFail(e.eMessage)
                    }
                }

            })
    }

    private fun eventConfig() {
        iv_phone_clear.setOnClickListener { edit_phone.text = null }
        switch_password.setOnClickListener {
            if (edit_password.transformationMethod == PasswordTransformationMethod.getInstance()) {
                switch_password.setImageResource(R.drawable.iv_login_visible)
                edit_password.transformationMethod = HideReturnsTransformationMethod.getInstance()
            } else {
                switch_password.setImageResource(R.drawable.iv_login_invisible)
                edit_password.transformationMethod = PasswordTransformationMethod.getInstance()
            }
        }

        btn_login.setOnClickListener {
            passwordLogin(
                edit_phone.text.toString(),
                edit_password.text.toString()
            )
        }
        btn_login_esm.setOnClickListener {
            startActivity<LoginPhoneActivity> { }
        }
        btn_forget_password.setOnClickListener {
            startActivity<ForgetPhoneActivity> { }
        }
    }

    private fun passwordLogin(phone: String, password: String) {
        when {
            phone.isEmpty() -> showSoftInput(edit_phone).apply { tipWarn(R.string.login_phone_empty) }
            !phone.regex(RegexConstants.REGEX_MOBILE_EXACT) -> showSoftInput(edit_phone).apply {
                tipWarn(
                    R.string.login_phone_wrong
                )
            }
            password.isEmpty() -> showSoftInput(edit_password).apply { tipWarn(R.string.login_password_empty) }
            password.length < 8 -> showSoftInput(edit_password).apply { tipWarn("密码最少位8位") }
            !password.regex(REGEX_PASSWORD) -> showSoftInput(edit_password).apply { tipWarn(R.string.login_password_wrong) }
            else -> {
                lifecycleScope.request({
                    APIAccount.service().login(phone, 1, password = password)
                }, object : BaseAPI<LoginEntity>() {

                    override fun onError(e: APIException) {
                        if (e.code == "-9") {
                            tipWarn("没有这个手机号的账户，如未注册，请选择动态密码登录")
                        } else {
                            tipFail(e.eMessage)
                        }
                    }

                    override fun onSuccess(loginEntity: LoginEntity?, state: Int, msg: String) {
                        tipSuccess(msg)
                        SP.isLogin.put(true)
                        SP.key_id.put(loginEntity?.key_id)
                        SP.account.put(loginEntity?.account)
                        SP.avatar.put(loginEntity?.avatar)
                        SP.EBusinessID.put(loginEntity?.business_id)
                        SP.AppKey.put(loginEntity?.app_key)
                        SP.ReqURL.put(loginEntity?.req_url)
//                        if (!SP.ISYinsi.get()) {
//                            startActivity<WebNoTokenActivity> {
//                                putExtra(URL, "http://beauty.hebzd.com/static/xieyi/privacy.html")
//                                putExtra(TITLE, "隐私协议")
//                            }
//                        } else {
                            startActivity<MainActivity> { }
//                        }
                        finish()
                    }
                })
            }
        }
    }
}